package com.wq.jdk8;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @Author: wangqiang20995
 * @Date:2019/7/11
 * @Description:
 * @Resource:
 */
public class FileInOutResolver {

    private final String charSet;

    public FileInOutResolver(String charset){
        this.charSet = charset;
    }

    public FileInOutResolver(){
        this(Charset.defaultCharset().displayName());
    }

    public String readFromFile(String path,String fileName) throws IOException {
        StringBuilder builder = new StringBuilder();

        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(path + File.separator + fileName),this.charSet));
            String line;
            while ((line = reader.readLine()) != null){
                builder.append(line);
            }

            return builder.toString();
        }finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public boolean writeToFile(String path,String fileName,String content) throws IOException {
        OutputStream outputStream = null;

        try{
            File file = new File(path + File.separator + fileName);
            if(!file.exists()){
                System.out.println("create file:" + path + File.separator + fileName);
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);

            byte[] data = content.getBytes(this.charSet);
            outputStream.write(data);

            //
            outputStream.flush();

            return true;
        }finally {
            if(outputStream != null){
                outputStream.close();
            }
        }
    }

    public static void main(String[] args){
        FileInOutResolver resolver = new FileInOutResolver();
        try {
            String reader = resolver.readFromFile("D://logs","error.log");

            resolver.writeToFile("D://logs","hello.txt",reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
